package org.jadelyre.lyre;

import org.jadelyre.core.Channel;
import org.jadelyre.core.JadeLyre;
import org.jadelyre.core.exception.JadeLyreException;
import org.jadelyre.core.task.Task;
import org.jadelyre.core.worker.Schedule;
import org.jadelyre.core.worker.Worker;

import java.io.IOException;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ScheduledFuture;

public class LyreCloseTask extends Task<Channel> {

    public LyreCloseTask(Worker<Channel> worker) {
        super(worker);
    }

    @Override
    protected <T> void work(T t) throws JadeLyreException {
        Channel channel = (Channel) t;
        JadeLyre jadeLyre = channel.getJadeLyre();
        LyreClient lyreClient = (LyreClient) jadeLyre;
        lyreClient.setStarted(false);
        channel.getDecodeWorker().setTerminated(true);
        channel.getHandleWorker().setTerminated(true);
        channel.getSendWorker().setTerminated(true);
        AsynchronousSocketChannel asynchronousSocketChannel = channel.getAsynchronousSocketChannel();
        try {
            if (asynchronousSocketChannel.isOpen()) {
                asynchronousSocketChannel.shutdownInput().shutdownOutput().close();
            }
        } catch (IOException e) {
            throw new JadeLyreException(e);
        }
        ClientConfig clientConfig = (ClientConfig) lyreClient.getJadeLyreConfig();
        if (clientConfig.getReconnectConfig().isEnable() && !lyreClient.isFirstConnect()) {
            lyreClient.connect();
        }
    }

}
